from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection

from .models import Spit
from .spit_serializers import SpitModelSerializer
from .utils import handel_list


class CommentView(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = Spit.objects.exclude(parent=None)
    serializer_class = SpitModelSerializer

    def my_list(self, request, pk):
        user = request.user

        queryset = self.queryset.filter(parent_id=pk)

        serializer = self.get_serializer(queryset, many=True)

        handel_list(serializer, user)

        return Response(serializer.data)


class SpitView(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = Spit.objects.filter(parent=None)
    serializer_class = SpitModelSerializer

    def my_retrieve(self, request, pk):
        user = request.user
        instance = self.get_object()

        serializer = self.get_serializer(instance)

        data = handel_list(serializer, user)

        return Response(data)

    def my_list(self, request):
        user = request.user

        queryset = self.get_queryset()

        serializer = self.get_serializer(queryset, many=True)

        for _dict in serializer.data:
            _dict['comment'] = [
                {'id': 1, 'title': '评论一'},
                {'id': 2, 'title': '评论二'},
            ]

        handel_list(serializer, user)

        return Response(serializer.data)

    def new_spit_comment(self, request):
        user = request.user
        parent = request.data.get('parent')
        if parent:
            request.data['userid'] = user.id
            request.data['nickname'] = user.nickname
            request.data['avatar'] = user.avatar

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


class HandelCollectedHasthumbupView(GenericAPIView):
    permission_classes = (IsAuthenticated,)
    queryset = Spit.objects.all()
    serializer_class = SpitModelSerializer

    def put(self, request, pk):
        user = request.user

        instance = self.get_object()
        data = {}

        def handel_data(instance, field, user):
            conn = get_redis_connection('collect_thumbup')

            _list = [int(i) for i in conn.smembers(f'{field}_{user.id}')]
            if instance.id in _list:
                rs = False
                conn.srem(f'{field}_{user.id}', instance.id)
            else:
                rs = True
                conn.sadd(f'{field}_{user.id}', instance.id)

            return rs

        if request.path.split('/')[3] == 'collect':

            handel_data(instance, 'collected', user)

        elif request.path.split('/')[3] == 'updatethumbup':

            thumbup = instance.thumbup
            rs = handel_data(instance, 'hasthumbup', user)
            data['thumbup'] = thumbup + 1 if rs else thumbup - 1

        else:
            raise ValidationError('路径错误')

        serializer = self.get_serializer(instance, data=data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({
            'message': '修改成功',
            'success': True,
        })



